package content

import (
	"fmt"
	"github.com/Exleryz/gorequest"
	"github.com/Exleryz/m3u8/util"
	"io"
	"net/url"
	"os"
)

// GetM3U8Content 获取m3u8内容
type GetM3U8Content interface {
	GetContent(str string) (string, error)
	ParseUrl(str string) bool
}

var getContentList []GetM3U8Content

var _ GetM3U8Content = (*httpM3U8)(nil)
var _ GetM3U8Content = (*fileM3U8)(nil)

var hg = &httpM3U8{}
var fg = &fileM3U8{}

func init() {
	getContentList = make([]GetM3U8Content, 0)
	getContentList = append(getContentList, hg, fg)
}

func NewGetM3U8Content(str string) GetM3U8Content {
	// 根据url判断
	for i := range getContentList {
		if getContentList[i].ParseUrl(str) {
			return getContentList[i]
		}
	}

	panic("no m3u8 get: " + str)
}

type httpM3U8 struct {
	url string
}

func (h httpM3U8) ParseUrl(str string) bool {
	_, err := url.ParseRequestURI(str)
	if err != nil {
		return false
	}
	return true
}

func (h httpM3U8) GetContent(str string) (string, error) {
	req := util.NewRequest(gorequest.New().Get(str))
	_, s, errors := req.End()
	// todo judge http status
	if len(errors) != 0 {
		if len(errors) == 1 && errors[0] == io.EOF {
		} else {
			fmt.Println(errors)
			return "", errors[0]
		}
	}

	return s, nil
}

type fileM3U8 struct {
	path string
}

func (f fileM3U8) ParseUrl(str string) bool {
	_, err := os.ReadFile(str)
	if err != nil {
		return false
	}
	return true
}

func (f fileM3U8) GetContent(str string) (string, error) {
	// 判断路径是否存在
	file, err := os.ReadFile(str)
	if err != nil {
		return "", err
	}

	// 获取文件
	return string(file), nil
}
